import os
import pathlib
import random
import sys
from datetime import timedelta
import django
import faker
from django.utils import timezone

# 将项目更目录添加到Python的模块搜索中
back = os.path.dirname
BASE_DIR = back(back(os.path.abspath(__file__)))
sys.path.append(BASE_DIR)

if __name__ == '__main__':
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "SimpleAdmin.settings")
    django.setup()
    from article.models import Article, Category, Tag
    from comment.models import Comment
    from django.contrib.auth.models import User

    print('开始清除数据库数据')
    Article.objects.all().delete()
    Category.objects.all().delete()
    Tag.objects.all().delete()
    Comment.objects.all().delete()
    print("数据清除完毕！")
    print("创建用户")
    user = User.objects.create_superuser('admin_admin1', 'admin@admin.com', 'admin')
    category_list = ['Python学习笔记', '开源项目', '工具资源', '程序员生活感悟', 'test category']
    tag_list = ['django', 'Python', 'Pipenv', 'Docker', 'Nginx', 'Elasticsearch', 'Gunicorn', 'Supervisor', '黄色']
    a_year_ago = timezone.now() - timedelta(days=365)
    print("生成博客分类和标签")
    for cate in category_list:
        Category.objects.create(title=cate)
    for tag in tag_list:
        Tag.objects.create(text=tag)
    print("生成博客文章")
    Article.objects.create(
        title='Markdown 与代码高亮测试',
        # body参数，添加文件名称，生成markdwon的测试md.sample 是一个纯文本文件
        body=pathlib.Path(BASE_DIR).joinpath('utils', 'md.sample').read_text(encoding='utf-8'),
        category=Category.objects.create(title='Markdown测试'),
        # tags=Tag.objects.create(text='黄色'),
        author=user,
    )
    print('使用Faker生成模拟数据')
    fake = faker.Faker('zh_CN')
    for _ in range(100):
        tags = Tag.objects.order_by('?')
        tag1 = tags.first()
        tag2 = tags.last()
        cate = Category.objects.order_by('?').first()
        created_time = fake.date_time_between(start_date='-1y', end_date="now",
                                              tzinfo=timezone.get_current_timezone())

        article = Article.objects.create(
            title=fake.sentence().rstrip('.'),
            body='\n\n'.join(fake.paragraphs(10)),
            # created=created_time,
            category=cate,
            author=user,
        )
        article.tags.add(tag1, tag2)
        article.save()

    print('生成评论数据')
    for article in Article.objects.all()[:20]:
        post_created_time = article.created
        delta_in_days = '-' + str((timezone.now() - post_created_time).days) + 'd'
        for _ in range(random.randrange(3, 15)):
            Comment.objects.create(
                author=user,
                content=fake.paragraph(),
                # created=fake.date_time_between(
                #     start_date=delta_in_days,
                #     end_date="now",
                #     tzinfo=timezone.get_current_timezone()),
                article=article,
            )
    print("数据生成完毕")
